<template>
  <div class="layout" @mouseup="mouseupcontWid">
    <!-- 左侧布局 -->
    <div
      v-if="toolIsShow"
      class="layout-left"
      :style="{ width: widthLeftForTools + 'px' }"
    >
      <el-tabs type="border-card" :stretch="true">
        <!-- 左侧组件栏-->
        <el-tab-pane label="工具栏">
          <draggable
            v-for="widget in widgetTools"
            :key="widget.code"
            @end="(evt) => widgetOnDragged(evt, widget.code)"
          >
            <div class="tools-item">
              <span class="tools-item-icon">
                <i class="iconfont" :class="widget.icon"></i>
              </span>
              <span class="tools-item-text">{{ widget.label }}</span>
            </div>
          </draggable>
        </el-tab-pane>
        <!-- 左侧图层-->
        <el-tab-pane label="图层">
          <draggable
            v-model="layerWidget"
            @update="datadragEnd"
            :options="{ animation: 300 }"
          >
            <transition-group>
              <div
                v-for="item in layerWidget"
                :key="item.id"
                class="tools-item"
                :class="widgetIndex.includes(item.id) ? 'is-active' : ''"
                @click="layerClick(item.widget)"
              >
                <span class="tools-item-icon">
                  <i class="iconfont" :class="item.icon"></i>
                </span>
                <span class="tools-item-text">{{ item.label }}</span>
              </div>
            </transition-group>
          </draggable>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 左侧折叠箭头 -->
    <div
      class="layout-left-fold"
      :style="{ width: widthLeftForToolsHideButton + 'px' }"
      @click="toolIsShow = !toolIsShow"
    >
      <i class="el-icon-arrow-right" />
    </div>

    <!-- 中间布局 -->
    <div
      class="layout-middle"
      :style="{ width: middleWidth + 'px', height: middleHeight + 'px' }"
    >
      <!-- 头部导航 -->
      <div class="top-button">
        <span style="flex: 1; color: #fff; margin-left: 14%">{{
          dashboard.title || "大屏标题"
        }}</span>
        <!-- <span class="btn">
          <el-tooltip
            class="item"
            effect="dark"
            content="重新提交"
            placement="bottom"
          >
            <i class="iconfont iconsave" @click="resetSaveData"></i>
          </el-tooltip>
        </span> -->
        <span class="btn">
          <el-tooltip
            class="item"
            effect="dark"
            :content="grade ? '隐藏网格' : '显示网格'"
            placement="bottom"
            style="font-size: 14px"
          >
            <i
              :class="grade ? 'el-icon-s-grid' : 'el-icon-full-screen'"
              @click="grade = !grade"
            ></i>
          </el-tooltip>
        </span>
        <span class="btn">
          <el-tooltip
            class="item"
            effect="dark"
            content="保存"
            placement="bottom"
          >
            <i class="iconfont iconsave" @click="saveData(false)"></i>
          </el-tooltip>
        </span>
        <span class="btn">
          <el-tooltip
            class="item"
            effect="dark"
            content="预览"
            placement="bottom"
          >
            <i class="iconfont iconyulan" @click="viewScreen()"></i>
          </el-tooltip>
        </span>
        <span class="btn">
          <el-tooltip
            class="item"
            effect="dark"
            content="发布"
            placement="bottom"
          >
            <i class="el-icon-s-promotion" @click="publishData"></i>
          </el-tooltip>
        </span>
      </div>
      <!-- 中间画布 -->
      <div
        class="bigscreenWorkbench"
        :style="{
          width: bigscreenWidthInWorkbench - widthPaddingTools + rulerState.thick + 1 + 'px',
          height: bigscreenHeightInWorkbench- widthPaddingTools + rulerState.thick + 1 + 'px',// 'calc(100vh - 63px)',
        }"
      >
        <div class="refer-line-img" @click="rulerState.isShowReferLine = !rulerState.isShowReferLine">
          <img class="img1" v-if="rulerState.isShowReferLine" src="">
          <img class="img2" v-else src="">
        </div>
        <!-- 刻度尺 -->
        <SketchRule
          class="sketchRule"
          :lang="rulerState.lang"
          :thick="rulerState.thick"
          :scale="rulerState.scale"
          :width="rulerState.width"
          :height="rulerState.height"
          :startX="rulerState.startX"
          :startY="rulerState.startY"
          :shadow="shadow"
          :horLineArr="rulerState.lines.h"
          :verLineArr="rulerState.lines.v"
          :cornerActive="true"
          :isShowReferLine="rulerState.isShowReferLine"
          @handleLine="handleLine"
          @onCornerClick="handleCornerClick"
          :palette="{bgColor: '#13161d',longfgColor: '#BABBBC',shortfgColor: '#C8CDD0',fontColor: '#efefef', shadowColor: '#666',lineColor: '#EB5648', borderColor: '#DADADC',cornerActiveColor: 'rgb(235, 86, 72, 0.6)',}"
        >
        </SketchRule>
        <!-- 可视滚动区域 -->
        <div
          class="workbench-container"
          :style="{
            width: bigscreenWidthInWorkbench - widthPaddingTools + 8 + 'px',
            height: bigscreenHeightInWorkbench- widthPaddingTools + 8  + 'px',
          }"
          @mousewheel="rollImg"
          @scroll="handleScroll"
        >
          <!-- 大画布 -->
          <div class="screen-container" @mousedown.self="mousedowncont" @mouseup.self="mouseupcont">
            <!-- 拖选框 -->
            <div class="rectDiv" @mousedown.self="mousedowncont" @mouseup.self="mouseupcont"></div>
            <!-- 画布缩放dom -->
            <div
              class="canvash"
              :style="{
                width: dashboard.width * bigscreenScaleInWorkbench + 'px',
                height: dashboard.height * bigscreenScaleInWorkbench + 'px',
                transform: workbenchScaleTrom
              }"
            >
              <!-- 工作画布自动计算百分比 -->
              <div
                id="workbench"
                class="workbench"
                :style="{
                  transform: workbenchTransform,
                  width: dashboard.width + 'px',
                  height: dashboard.height + 'px',
                  'background-color': dashboard.backgroundColor,
                  'background-image': 'url(' + dashboard.backgroundImage + token + ')',
                  'background-position': '0% 0%',
                  'background-size': '100% 100%',
                  'background-repeat': 'initial',
                  'background-attachment': 'initial',
                  'background-origin': 'initial',
                  'background-clip': 'initial',
                  margin: '0px',
                }"
                @mousedown.self="mousedowncont"
                @mouseup.self="mouseupcont"
              >
                <!-- 网格 -->
                <div v-if="grade" class="bg-grid" @mousedown.self="mousedowncont" @mouseup.self="mouseupcont"></div>
                <!-- 组件 -->
                <widget
                  ref="widgets"
                  v-for="(widget, index) in widgets"
                  :key="index"
                  v-model="widget.value"
                  :index="index"
                  :type="widget.type"
                  :widgetComponent="widgetComponent"
                  :bigscreen="{ bigscreenWidth, bigscreenHeight }"
                  @contextmenu.prevent.native="rightClick($event, index, widget.value.position.zIndex)"
                  @mouseup.native="mouseupcontWid"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 尾部说明 -->
      <div class="footer">Tip: 空格 + 鼠标左键：拖动画布，Alt + 鼠标滚轮：缩放画布，Ctrl + 左键：多选组件，右键：呼出自定义菜单，画布上拖动鼠标框选组件，拖动图层排序，标尺眼睛隐藏辅助线</div>
    </div>

    <!-- 右侧 -->
    <div class="layout-right" :style="{ width: widthLeftForOptions + 'px' }">
      <el-tabs v-model="activeName" type="border-card" :stretch="true">
        <!-- 多选显示对齐方式 -->
        <el-tab-pane v-if="widgetIndex.length > 1" name="multiple" label="对齐方式">
          <MultipleForm />
        </el-tab-pane>
        <el-tab-pane
          v-if="
            (widgetIndex.length <= 1 && isNotNull(widgetOptions.setup)) ||
            isNotNull(widgetOptions.collapse)
          "
          name="first"
          label="配置"
        >
          <dynamicForm
            ref="formData"
            :options="widgetOptions.setup"
            @onChanged="(val) => widgetValueChanged('setup', val)"
          />
        </el-tab-pane>
        <el-tab-pane
          v-if="widgetIndex.length <= 1 && isNotNull(widgetOptions.data)"
          name="second"
          label="数据"
        >
          <dynamicForm
            ref="formData"
            :options="widgetOptions.data"
            @onChanged="(val) => widgetValueChanged('data', val)"
          />
        </el-tab-pane>
        <el-tab-pane
          v-if="widgetIndex.length <= 1 && isNotNull(widgetOptions.position)"
          name="third"
          label="坐标"
        >
          <dynamicForm
            ref="formData"
            :options="widgetOptions.position"
            @onChanged="(val) => widgetValueChanged('position', val)"
          />
        </el-tab-pane>
      </el-tabs>
    </div>
    <!-- 右键菜单 -->
    <content-menu
      :visible.sync="visibleContentMenu"
      :style-obj="styleObj"
      @deletelayer="deletelayer"
      @copylayer="copylayer"
      @istopLayer="istopLayer"
      @setlowLayer="setlowLayer"
      @moveupLayer="moveupLayer"
      @movedownLayer="movedownLayer"
    />
  </div>
</template>

<script>
import { mapState } from "vuex";
import { addBigscreen, editBigscreen, detailDashboard } from "@/api/bigscreen"; // 接口
import SketchRule from 'vue-sketch-ruler' // 大屏设计页面的标尺插件
import { widgetTools, getToolByCode } from "./tools/index"; // 获取工具栏和图层数据
import widget from "./widget/widget.vue"; // 组件
import dynamicForm from "./designerComponents/dynamicForm.vue"; // 配置动态组件
import MultipleForm from "./designerComponents/MultipleForm.vue"; // 配置多选组件
import draggable from "vuedraggable"; // 拖拽组件
import contentMenu from "./designerComponents/contentMenu"; // 菜单内容
import { getToken } from '@/utils/auth';
export default {
  name: "designer",
  // 向下传递数据
  provide() {
    return {
      designerComponent: this,
    };
  },
  components: {
    draggable,
    widget,
    dynamicForm,
    contentMenu,
    MultipleForm,
    SketchRule
  },
  data() {
    return {
      token: `&Authorization=${getToken()}`,
      lgc_sn: "", // 大屏id
      grade: false, // 网格是否显示
      bodyWidth: "", // 可视窗口的宽度
      bodyHeight: "", // 可视窗口的高度
      // 左侧工具栏
      toolIsShow: true, // 工具栏是否显示
      widthLeftForTools: 180, // 工具栏宽度
      widthLeftForToolsHideButton: 15, // 工具栏折叠按钮宽度
      layerWidget: [], // 图层数据
      widgetTools: widgetTools, // 工具栏数据

      // 右侧配置
      activeName: "first", // 当前激活的tab
      widthLeftForOptions: 290, // 右侧配置栏宽度
      widthPaddingTools: 30,

      // 中间画布
      bigscreenWidth: 1920, // 大屏宽度
      bigscreenHeight: 1080, // 大屏高度
      screenCode: "", // 大屏的标记，判断点击的是大屏还是组件
      workbenchScale: 0.9, // 鼠标滚轮控制中间画布的缩放比例
      // **重要：工作台大屏画布提交的数据
      dashboard: {
        id: null,
        title: "", // 大屏页面标题
        width: 1920, // 大屏设计宽度
        height: 1080, // 大屏设计高度
        backgroundColor: "#0e2a42", // 大屏背景色
        backgroundImage: "", // 大屏背景图片
      },
      // **重要：工作区中拖放的组件, 提交的数据
      widgets: [
        {
          type: "widget-text", // 组件类型
          value: { // 大屏组件配置
            setup: {}, // 样式
            data: {}, // 数据
            position: { // 位置
              width: 100,
              height: 100,
              left: 0,
              top: 0,
              zIndex: 0,
            },
          },
          options: [],// 组件右侧配置，内容同value
        },
      ],

      // 组件
      widgetIndex: [], // 当前激活组件id的数组
      widgetComponent: [], // 当前激活的组件所有配置的数组
      widgetOptions: { // 当前激活组件右侧配置属性
        setup: [], // 配置
        data: [], // 数据
        position: [], // 坐标
      },

      // 点击右键
      styleObj: { // 点击右键自定义菜单位置对象
        left: 0,
        top: 0,
      },
      visibleContentMenu: false, // 菜单是否显示
      rightClickIndex: -1, // 当前点击组件在widgets中的index
      rightClickzIndex: -1, // 当前点击组件的zIndex,用于调整层级

      // 拖动，缩放画布
      // 监听键盘事件
      keys: {
        ctrl: false,
        space: false,
        alt: false,
      },

      // 记录鼠标按下的位置
      mouseDownPosition: {
        left: 0,
        top: 0,
      },
      // 控制画布canvash的位置
      offsetTop: 0,
      offsetLeft: 0,
      scrollTop: 0,
      scrollLeft: 0,
      // 刻度尺数据
      rulerState: {
        scale: 1, // 缩放比例
        startX: 0, // 刻度尺x轴的便宜距离
        startY: 0, // 刻度尺y轴的便宜距离
        initStartX: 0, // X初始偏移量
        initStartY: 0, // Y初始偏移量
        lines: { // 辅助线数组
          h: [100],
          v: [100]
        },
        thick: 20, // 刻度的宽度
        width: 0, // 刻度尺的宽度
        height: 0, // 刻度尺的高度
        lang: "zh-CN", // 中英文
        isShowRuler: true, // 显示标尺
        isShowReferLine: true // 显示参考线
      },
      timer: null
    };
  },
  computed: {
    ...mapState("user", ["userInfo"]),
    // 标尺阴影配置
    shadow() {
      return {
        x: 0,
        y: 0,
        width: this.bigscreenWidthInWorkbench - this.widthPaddingTools,
        height: this.bigscreenHeightInWorkbench - this.widthPaddingTools
      }
    },
    // 计算画布缩放之后的比例，控制拖拽组件鼠标移动速度
    stepScale() {
      let scale = Number(((1 / (this.bigscreenScaleInWorkbench * this.workbenchScale * 100)) * 100).toFixed(2));
      return scale;
    },
    // 鼠标滚动画布的缩放比例
    workbenchScaleTrom() {
      return `scale(${this.workbenchScale}, ${this.workbenchScale})`
    },
    // 左侧折叠切换时，动态计算中间区的宽度
    middleWidth() {
      var widthLeftAndRight = 0;
      if (this.toolIsShow) {
        widthLeftAndRight += this.widthLeftForTools; // 左侧工具栏宽度\
      }
      widthLeftAndRight += this.widthLeftForToolsHideButton; // 左侧工具栏折叠按钮宽度
      widthLeftAndRight += this.widthLeftForOptions; // 右侧配置栏宽度
      var middleWidth = this.bodyWidth - widthLeftAndRight;
      return middleWidth;
    },
    middleHeight() {
      return this.bodyHeight;
    },
    // 设计台按大屏的缩放比例
    bigscreenScaleInWorkbench() {
      var widthScale =
        this.getFixed((this.middleWidth - this.widthPaddingTools) / this.bigscreenWidth);
      var heightScale =
        this.getFixed((this.middleHeight - this.widthPaddingTools) / this.bigscreenHeight);
      return Math.min(widthScale, heightScale);
    },
    // 设计台按大屏的缩放样式
    workbenchTransform() {
      return `scale(${this.bigscreenScaleInWorkbench}, ${this.bigscreenScaleInWorkbench})`;
    },
    // 大屏在设计模式的大小
    bigscreenWidthInWorkbench() {
      return this.getPXUnderScale(this.bigscreenWidth) + this.widthPaddingTools;
    },
    bigscreenHeightInWorkbench() {
      return (
        this.getPXUnderScale(this.bigscreenHeight) + this.widthPaddingTools
      );
    },
  },
  watch: {
    widgets: {
      handler(val) {
        // 深度监听组件变化增加组件图层
        this.handlerLayerWidget(val);
        const index = val.map(item => ({
          name: item.type,
          index: item.value.position.zIndex
        }))
        console.log('排序', index);
      },
      immediate: true,
      deep: true,
    },
    'keys.space': {
      handler(val) {
        this.$nextTick(() => {
          // 按下空格鼠标变成手
          if(val) {
            document.querySelector('.screen-container').style.cursor = 'grab'
          } else {
            document.querySelector('.screen-container').style.cursor = 'default'
          }
        })
      },
      immediate: true
    },
  },
  mounted() {
    // 画布位置，标尺初始化
    this.initScroll()
    // 初始化键盘监听事件
    this.listenKeys();
    // 初始化大屏和组件的数据
    this.initEchartData();
    // 初始化视口的宽度
    this.bodyWidth = document.body.clientWidth;
    this.bodyHeight = document.body.clientHeight;
    // 窗口缩放动态计算
    window.addEventListener("resize", () => {
      this.bodyWidth = document.body.clientWidth;
      this.bodyHeight = document.body.clientHeight;
    });
    // this.timer = setInterval(() => {
    //   if(!this.widgets || this.widgets.length == 0) return
    //   this.saveData(true)
    // }, 1000 * 10)
  },
  beforeDestroy() {
    clearInterval(this.timer)
  },
  methods: {
    /***************初始化相关*****************/
    // 初始化画布的位置，保证画布在中间显示
    initScroll() {
      this.$nextTick(() => {
        // 初始化滚动条的位置，拖动会改变
        this.offsetTop = document.querySelector('.canvash').offsetTop
        this.offsetLeft = document.querySelector('.canvash').offsetLeft
        document.querySelector('.workbench-container').scrollTo(this.offsetLeft, this.offsetTop);
        // 记录画布的初始位置，拖动不改变
        this.scrollTop = document.querySelector('.workbench-container').scrollTop;
        this.scrollLeft = document.querySelector('.workbench-container').scrollLeft;
        //初始化标尺的宽度和位置，宽高等于大屏的宽高即可
        this.rulerState.width = this.bigscreenWidthInWorkbench - this.widthPaddingTools;
        this.rulerState.height = this.bigscreenHeightInWorkbench - this.widthPaddingTools;
        this.rulerState.scale = this.workbenchScale
      })
    },
    // 初始化键盘鉴定事件
    listenKeys() {
      function hander(event) {
        event.preventDefault()
      }
      // 监听键盘按下
      document.onkeydown = (event) => {
        var e = event || window.event || arguments.callee.caller.arguments[0];
        // 监听按键
        this.keys.ctrl = e && e.keyCode === 17;
        this.keys.alt = e && e.keyCode === 18;
        this.keys.space = e && e.keyCode === 32;
        if(e && e.keyCode === 32) {
          e.preventDefault()
        }
        // 按下alt禁止鼠标滚轮默认事件
        if(e && e.keyCode === 18){
          document.querySelector('.workbench-container').addEventListener('mousewheel', hander, false)
        }
        // ctrl+d复制组件
        if(e.ctrlKey && e.keyCode === 68){
          this.copylayer()
          e.preventDefault()
        }
        // vtrl+s保存
        if(e.ctrlKey && e.keyCode === 83){
          this.saveData(false)
          e.preventDefault()
        }
        // 组件的微调移动
        this.handleMoveLittle(e.keyCode, e)
      };
      // 监听键盘抬起
      document.onkeyup = (e) => {
        this.keys.ctrl = false;
        this.keys.alt = false;
        this.keys.space = false;
        this.keys.d = false;
        // 抬起按键恢复滚轮功能
        document.querySelector('.workbench-container').removeEventListener('mousewheel', hander, false)
      };
    },
    /***************初始化数据*****************/
    // 0. 初始化大屏调详情接口
    initEchartData() {
      const reportCode = this.$route.params.id;
      this.lgc_sn = this.$route.params.id;
      let data = ''
      // 判断新增还是修改
      if (reportCode) {
        const loading = this.$loading({
          lock: true,
          text: "正在加载中，请稍后",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });
        detailDashboard(reportCode).then(({tx_status, content}) => {
          if (tx_status !== "00") return;
          data = JSON.parse(content || "");
          if (!data) return
          const processData = this.handleInitEchartsData(data); // 初始化组件数据
          const screenData = this.handleBigScreen(data.dashboard); // 初始化大屏数据
          this.widgets = processData; // 组件数据
          this.dashboard = screenData; // 大屏数据
          this.rulerState.lines = data.lines || { h: [100], v: [100] }
        }).finally(() => {
          loading.close();
        })
      } else {
        data = {
          dashboard: {
            title: this.$route.query.title,
            width: this.$route.query.width,
            height: this.$route.query.height,
            backgroundColor: "#0e2a42",
            backgroundImage: "",
          },
          widgets: [],
        };
        if (!data) return
        const processData = this.handleInitEchartsData(data); // 初始化组件数据
        const screenData = this.handleBigScreen(data.dashboard); // 初始化大屏数据
        this.widgets = processData; // 组件数据
        this.dashboard = screenData; // 大屏数据
        this.rulerState.lines = data.lines || { h: [100], v: [100] }
      }
    },
    // 1. 初始化组件数据
    handleInitEchartsData(data) {
      const widgets = data ? data.widgets : [];
      const widgetsData = [];
      for (let i = 0; i < widgets.length; i++) {
        var obj = {};
        obj.id = widgets[i].id;
        obj.type = widgets[i].type;
        obj.value = {
          setup: widgets[i].value.setup,
          data: widgets[i].value.data,
          position: widgets[i].value.position,
        };
        const tool = this.deepClone(getToolByCode(widgets[i].type));
        const option = tool.options;
        const options = this.handleOptionsData(widgets[i].value, option);
        obj.options = options;
        widgetsData.push(obj);
      }
      return widgetsData;
    },

    // 2. 初始化组件数据动态赋值为接口数据
    handleOptionsData(data, option) {
      for (const key in data.setup) {
        for (let i = 0; i < option.setup.length; i++) {
          let item = option.setup[i];
          if (Object.prototype.toString.call(item) == "[object Object]") {
            if (key == option.setup[i].name) {
              option.setup[i].value = data.setup[key];
            }
          } else if (Object.prototype.toString.call(item) == "[object Array]") {
            for (let j = 0; j < item.length; j++) {
              const list = item[j].list;
              list.forEach((el) => {
                if (key == el.name) {
                  el.value = data.setup[key];
                }
              });
            }
          }
        }
      }
      // position
      for (const key in data.position) {
        for (let i = 0; i < option.position.length; i++) {
          if (key == option.position[i].name) {
            option.position[i].value = data.position[key];
          }
        }
      }
      // data
      for (const key in data.data) {
        for (let i = 0; i < option.data.length; i++) {
          if (key == option.data[i].name) {
            option.data[i].value = data.data[key];
          }
        }
      }
      return option;
    },
    // 3. 初始化大屏数据
    handleBigScreen(data) {
      const optionScreen = getToolByCode("screen").options;
      const setup = optionScreen.setup;
      for (const key in data) {
        for (let i = 0; i < setup.length; i++) {
          if (key == setup[i].name) {
            setup[i].value = data[key];
          }
        }
      }
      // 默认展示大屏配置
      this.setOptionsOnClickScreen();
      return {
        backgroundColor: (data && data.backgroundColor) || "",
        backgroundImage: (data && data.backgroundImage) || "",
        height: (data && data.height) || "",
        title: (data && data.title) || "",
        width: (data && data.width) || "",
      };
    },
    // 4. 如果是点击大屏设计器中的底层，加载大屏底层属性
    setOptionsOnClickScreen() {
      this.screenCode = "screen";
      this.widgetOptions = getToolByCode("screen")["options"];
      // 选中不同的组件 右侧都显示第一栏，清楚激活的组件
      this.activeName = "first";
      this.widgetIndex = [];
      this.widgetComponent = [];
      const draggableArr = this.$refs.widgets;
      for (let i = 0; i < draggableArr.length; i++) {
        this.$refs.widgets[i].$refs.draggable.setActive(false);
      }
    },
    // 组件widgets变化, 同步图层数组
    handlerLayerWidget(val) {
      const layerWidgetArr = [];
      for (let i = 0; i < val.length; i++) {
        const obj = {};
        obj.icon = getToolByCode(val[i].type).icon;
        obj.id = val[i].id;
        obj.widget = val[i];
        const options = val[i].options["setup"];
        options && options.forEach((el) => {
          if (el.name == "layerName") {
            obj.label = el.value;
          }
        });
        layerWidgetArr.push(obj);
      }
      this.layerWidget = layerWidgetArr;
    },

    /***************保存发布相关*****************/
    // 保存的时候生成快照
    createImage() {
      return new Promise((resolve, reject) => {
        this.$nextTick(() => {
          // 生成快照
          html2canvas(document.getElementById("workbench"), {
            onrendered: (canvas) => {
              const res = canvas.toDataURL("image/jpeg", 1);
              resolve(res);
            },
          });
        });
      });
    },
    // 保存数据
    async saveData(flag) {
      if (!this.widgets || this.widgets.length == 0) {
        this.$message.error("请添加组件");
        return;
      }
      if(!flag) {
        this.$message.info("正在保存，请稍后！");
      }

      const coverImg = await this.createImage();
      const screenData = {
        coverImg,
        dashboard: {
          title: this.dashboard.title,
          width: this.dashboard.width,
          height: this.dashboard.height,
          backgroundColor: this.dashboard.backgroundColor,
          backgroundImage: this.dashboard.backgroundImage,
        },
        widgets: this.widgets,
        lines: this.rulerState.lines
      };

      // const loading = this.$loading({
      //   lock: true,
      //   text: "正在保存配置，请稍后",
      //   spinner: "el-icon-loading",
      //   background: "rgba(0, 0, 0, 0.7)",
      // });
      // 新增还是修改
      if (this.lgc_sn) {
        // 本地存储用于恢复提交
        // const screenDataString = JSON.stringify(screenData)
        // localStorage.setItem('screenData', screenDataString)
        editBigscreen({
          lgc_sn: this.lgc_sn,
          prov_cd: this.userInfo.prov_cd,
          city_cd: this.userInfo.city_cd,
          zon_cd: this.userInfo.zon_cd,
          name: this.dashboard.title,
          content: JSON.stringify(screenData),
          status: "0",
        }).then(res => {
          if (res.tx_status === "00") {
            this.$message.success("大屏配置保存成功！");
          } else {
            this.$message.error(res.error_info.msg || "请求失败");
          }
        }).finally(() => {
          // loading.close();
        })
      } else {
        addBigscreen({
          prov_cd: this.userInfo.prov_cd,
          city_cd: this.userInfo.city_cd,
          zon_cd: this.userInfo.zon_cd,
          name: this.dashboard.title,
          content: JSON.stringify(screenData),
          status: "0",
        }).then(res => {
          if (res.tx_status === "00") {
            this.$message.success("大屏配置保存成功！");
          } else {
            this.$message.error(res.error_info.msg || "请求失败");
          }
        }).finally(() => {
          // loading.close();
        })
      }
    },
    // 重新提交
    async resetSaveData() {
      this.widgets.push({
        id:'111',
        type: 'WidgetZuhe'
      })
      return
      const screenData = localStorage.getItem('screenData')
      const data = screenData ? JSON.parse(screenData) : {}
      console.log('data', data);
      const loading = this.$loading({
        lock: true,
        text: "正在保存配置，请稍后",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      editBigscreen(data).then(res => {
        if (res.tx_status === "00") {
          this.$message.success("大屏配置更新成功！");
        } else {
          this.$message.error(res.error_info.msg || "请求失败");
        }
      }).finally(() => {
        loading.close();
      })
    },
    // 发布
    publishData() {
      if (!this.widgets || this.widgets.length == 0) {
        this.$message.error("请添加组件");
        return;
      }
      this.$confirm(`确定发布此大屏配置吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        const screenData = {
          dashboard: {
            title: this.dashboard.title,
            width: this.dashboard.width,
            height: this.dashboard.height,
            backgroundColor: this.dashboard.backgroundColor,
            backgroundImage: this.dashboard.backgroundImage,
          },
          widgets: this.widgets,
        };
        const loading = this.$loading({
          lock: true,
          text: "正在发布配置，请稍后",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });
        // 新增还是修改
        if (this.lgc_sn) {
          editBigscreen({
            lgc_sn: this.lgc_sn,
            prov_cd: this.userInfo.prov_cd,
            city_cd: this.userInfo.city_cd,
            zon_cd: this.userInfo.zon_cd,
            name: this.dashboard.title,
            content: JSON.stringify(screenData),
            status: "1",
          }).then((res) => {
            if (res.tx_status === "00") {
              this.$message.success("大屏配置发布成功！");
            } else {
              this.$message.error(res.error_info.msg || "请求失败");
            }
          }).finally(() => {
            loading.close();
          })
        } else {
          addBigscreen({
            prov_cd: this.userInfo.prov_cd,
            city_cd: this.userInfo.city_cd,
            zon_cd: this.userInfo.zon_cd,
            name: this.dashboard.title,
            content: JSON.stringify(screenData),
            status: "1",
          }).then((res) => {
            if (res.tx_status === "00") {
              this.$message.success("大屏配置发布成功！");
              this.$router.push({
                path: "/micro/vueApply/bigscreen/list",
              });
            } else {
              this.$message.error(res.error_info.msg || "请求失败");
            }
          }).finally(() => {
            loading.close();
          })
        }
      });
    },
    // 预览
    async viewScreen() {
      await this.saveData(false);
      var routeUrl = this.$router.resolve({
        path: `/micro/vueApply/out/bigscreen/viewer/${this.lgc_sn}`,
      });
      window.open(routeUrl.href, "_blank");
    },

    /***************工具函数*****************/
    // 计算画布在缩放模式下的大小
    getPXUnderScale(px) {
      return this.bigscreenScaleInWorkbench * px;
    },
    //保留两位小数
    getFixed (val = 0, len = 2) {
      return Number(val.toFixed(len));
    },
    /***************新增点击组件*****************/
    // 1. 新增组件，拖动一个组件放到工作区中去，在拖动结束时，放到工作区对应的坐标点上去
    widgetOnDragged(evt, widgetCode) {
      var widgetType = widgetCode;

      // 获取结束坐标和列名
      var eventX = evt.originalEvent.clientX; // 结束在屏幕的x坐标
      var eventY = evt.originalEvent.clientY; // 结束在屏幕的y坐标

      var workbenchPosition = this.getDomTopLeftById("workbench"); // 获取dom在屏幕中的top和left
      var widgetTopInWorkbench = eventY - workbenchPosition.top;
      var widgetLeftInWorkbench = eventX - workbenchPosition.left;

      // 计算在缩放模式下的x y
      var x = widgetLeftInWorkbench / this.bigscreenScaleInWorkbench;
      var y = widgetTopInWorkbench / this.bigscreenScaleInWorkbench;
      // 复制一个组件
      var tool = getToolByCode(widgetType);
      var widgetJson = {
        id:'big' + Math.random() * 10 + +new Date(),
        type: widgetType,
        value: {
          setup: {},
          data: {},
          position: {
            width: 0,
            height: 0,
            left: parseInt(x),
            top: parseInt(y),
            zIndex: this.widgets.length,
          },
        },
        options: this.deepClone(tool.options),
      };
      // 处理默认值
      const widgetJsonValue = this.handleDefaultValue(widgetJson);
      // 将选中的复制组件，放到工作区中去
      this.widgets.unshift(this.deepClone(widgetJsonValue));
      // 激活新组件的配置属性
      this.layerClick(widgetJsonValue)
    },
    // 2. 对组件默认值处理
    handleDefaultValue(widgetJson) {
      for (const key in widgetJson) {
        if (key == "options") {
          // collapse、data、position、setup
          // setup 处理
          for (let i = 0; i < widgetJson.options.setup.length; i++) {
            const item = widgetJson.options.setup[i];
            if (Object.prototype.toString.call(item) == "[object Object]") {
              widgetJson.value.setup[item.name] = item.value;
            } else if (
              Object.prototype.toString.call(item) == "[object Array]"
            ) {
              for (let j = 0; j < item.length; j++) {
                const list = item[j].list;
                list.forEach((el) => {
                  widgetJson.value.setup[el.name] = el.value;
                });
              }
            }
          }
          // position
          for (let i = 0; i < widgetJson.options.position.length; i++) {
            const item = widgetJson.options.position[i];
            // left,top用widgetJson赋值，width,height用右侧配置的默认值赋值
            if (item.value) {
              widgetJson.value.position[item.name] = item.value;
            } else {
              item.value = widgetJson.value.position[item.name]
            }
          }
          // data 处理
          if (widgetJson.options.data && widgetJson.options.data.length > 0) {
            for (let i = 0; i < widgetJson.options.data.length; i++) {
              const item = widgetJson.options.data[i];
              if (item.value) {
                widgetJson.value.data[item.name] = item.value;
              }
            }
          }
        }
      }
      return widgetJson;
    },
    // 1. 点击图层，激活当前组件, 三种情况，1. 点击图层，2.点击组件 3.移动的时候触发
    // 参数：当前点击的组件，移动时候的位置信息，是移动还是点击
    layerClick(currWidget, obj = false, isMove = false, copy = false) {
      const id = currWidget.id
      // 不是移动是点击的时候
      if (!isMove) {
        // 监听ctrl多选
        if (this.keys.ctrl || copy) {
          // 如果当前激活组件大于1且包含当前点击项，移除当前点击项
          if (this.widgetIndex.length > 1 && this.widgetIndex.includes(id)) {
            this.widgetIndex = this.widgetIndex.filter(item => item !== id);
            this.widgetComponent = this.widgetComponent.filter(item => item.id !== id);
          } else {
            // 如果不是自己在添加
            if (!this.widgetIndex.includes(id)) {
              this.widgetIndex.push(id);
              this.widgetComponent.push(currWidget)
            };
          }
        } else {
          // 没有多选直接放入自己的id和组件信息
          this.widgetIndex = [id];
          this.widgetComponent = [currWidget]
        }
      }

      this.widgetsClick(currWidget, obj, isMove);
    },
    // 2. 当前高亮，显示网格
    widgetsClick(currWidget, obj, isMove) {
      this.$nextTick(() => {
        if(!isMove){
          for (let i = 0; i < this.widgets.length; i++) {
            if (this.widgetIndex.includes(this.widgets[i].id)) {
              this.$refs.widgets[i].$refs.draggable.setActive(true);
            } else {
              this.$refs.widgets[i].$refs.draggable.setActive(false);
            }
          }
        }
        this.setOptionsOnClickWidget(currWidget, obj, isMove);
      })

      // this.grade = true;
    },
    // 3. 如果是点击某个组件，获取该组件的配置项
    setOptionsOnClickWidget(currWidget, obj, isMove) {
      this.screenCode = "";
      if(!currWidget) return
      // 设置组件和配置位置信息同步
      const setObj = () => {
        currWidget.value.position = {
          left: obj.left,
          top: obj.top,
          width: obj.width,
          height: obj.height,
          zIndex: currWidget.value.position.zIndex
        };
        currWidget.options.position.forEach((el) => {
          for (const key in obj) {
            if (el.name == key) {
              el.value = obj[key];
            }
          }
        });
        this.activeName = "first";
        if(this.widgetIndex.length > 1) {
          this.activeName = "multiple";
        }
        this.widgetOptions = this.deepClone(currWidget["options"]);
      }
      // 如果是移动只设置位置信息，不设置高亮
      if(isMove) {
        setObj()
        return
      }

      // 判断点击的是组件还是，图层obj是点击组件时候的位置信息
      if (!obj) {
        this.widgetOptions = this.deepClone(currWidget["options"]);
        this.activeName = "first";
        if(this.widgetIndex.length > 1) {
          this.activeName = "multiple";
        }
        return;
      }
      setObj()
    },
    // 鼠标按下取消所有高亮
    handleMouseDown() {
      const draggableArr = this.$refs.widgets;
      for (let i = 0; i < draggableArr.length; i++) {
        this.$refs.widgets[i].$refs.draggable.setActive(false);
      }
      // 清空选中的组件id，组件，图层
      this.widgetIndex = [];
      this.widgetComponent = [];
    },
    // 1. 将当前选中的组件，更改右侧属性，大屏中的组件值同步更新
    widgetValueChanged(key, val) {
      if (this.screenCode == "screen") {
        this.dashboard = this.deepClone(val);
      } else {
        for (let i = 0; i < this.widgets.length; i++) {
          if (this.widgetIndex[0] == this.widgets[i].id) {
            this.widgets[i].value[key] = this.deepClone(val);
            this.setDefaultValue(this.widgets[i].options[key], val);
          }
        }
      }
    },
    // 2. 设置option的值
    setDefaultValue(options, val) {
      for (let i = 0; i < options.length; i++) {
        if (Object.prototype.toString.call(options[i]) == "[object Object]") {
          for (const k in val) {
            if (options[i].name == k) {
              options[i].value = val[k];
            }
          }
        } else if (Object.prototype.toString.call(options[i]) == "[object Array]") {
          for (let j = 0; j < options[i].length; j++) {
            const list = options[i][j].list;
            for (let z = 0; z < list.length; z++) {
              for (const k in val) {
                if (list[z].name == k) {
                  list[z].value = val[k];
                }
              }
            }
          }
        }
      }
    },

    /***************右键功能相关*****************/
    // 点击右键
    rightClick(event, index, zindex) {
      this.rightClickIndex = index;
      this.rightClickzIndex = zindex;
      const left = event.clientX;
      const top = event.clientY;
      if (left || top) {
        this.styleObj = {
          left: left + "px",
          top: top + "px",
          display: "block",
        };
      }
      this.visibleContentMenu = true;
      return false;
    },

    // 图层拖拽排序
    datadragEnd(evt) {
      evt.preventDefault();
      // 互换位置
      const widgets = this.swapArr(this.widgets, evt.oldIndex, evt.newIndex);
      // 重新排序zIndex
      this.widgets = widgets.map((item, index) => ({
        ...item,
        value: {
          ...item.value,
          position: {
            ...item.value.position,
            zIndex: this.widgets.length - 1 - index,
          }
        }
      }))
      // 重置高亮组件
      for (let i = 0; i < this.widgets.length; i++) {
        this.$refs.widgets[i].$refs.draggable.setActive(false);
      }
      this.$refs.widgets[evt.newIndex].$refs.draggable.setActive(true);
    },
    // 数组 元素互换位置
    swapArr(arr, oldIndex, newIndex) {
      this.widgets[oldIndex] = arr.splice(newIndex, 1, arr[oldIndex])[0];
      return arr;
    },
    // 删除所有选中项
    deletelayer() {
      this.widgetIndex.map(id => {
        const index = this.widgets.findIndex(item => item.id === id)
        this.widgets.splice(index, 1);
        this.setOptionsOnClickScreen();
      })
    },
    // 复制所有选中项
    copylayer() {
      const length = this.widgets.length
      const widgetIndex = [];
      const widgetComponent = [];
      // 复制高亮的选项，错位显示,翻转数组，重拍zindex
      this.widgetComponent.reverse().map((item, index) => {
        const obj = this.deepClone({
          ...item,
          id: 'big' + Math.random() * 10 + +new Date(),
          value: {
            ...item.value,
            position: {
              ...item.value.position,
              left: item.value.position.left + 100,
              top: item.value.position.top + 100,
              zIndex: length + index,
            }
          }
        });
        this.widgets.unshift(obj)
        widgetIndex.push(obj.id);
        widgetComponent.push(obj)
        this.layerClick(obj, false, false , true)
      })
        this.widgetIndex = widgetIndex
        this.widgetComponent = widgetComponent

    },
    // 置顶
    istopLayer() {
      // 最上层不移动
      if (this.rightClickzIndex >= this.widgets.length - 1) return
      // 排除自己
      const otherWidget = this.widgets.filter(item => item.id !== this.widgets[this.rightClickIndex].id);
      const currzIndex = this.widgets[this.rightClickIndex].value.position.zIndex
      // 当前选中项变为最大数
      this.widgets[this.rightClickIndex].value.position.zIndex = this.widgets.length - 1;
      // 如果大于当前项的zindex都减1
      otherWidget.map(item => {
        if(item.value.position.zIndex > currzIndex){
          item.value.position.zIndex -= 1
        }
      })
      // 取出选中项放到最上面
      this.widgets.unshift(this.widgets.splice(this.rightClickIndex, 1)[0]);
      // 重置高亮组件
      for (let i = 0; i < this.widgets.length; i++) {
        this.$refs.widgets[i].$refs.draggable.setActive(false);
      }
      this.$refs.widgets[0].$refs.draggable.setActive(true);
    },
    // 置底
    setlowLayer() {
      // 最下层不移动
      if (this.rightClickzIndex <= 0) return
      // 排除自己
      const otherWidget = this.widgets.filter(item => item.id !== this.widgets[this.rightClickIndex].id);
      const currzIndex = this.widgets[this.rightClickIndex].value.position.zIndex
      // 当前选中项变为0
      this.widgets[this.rightClickIndex].value.position.zIndex = 0;
      // 如果大于当前项的zindex都减1
      otherWidget.map(item => {
        if(item.value.position.zIndex < currzIndex){
          item.value.position.zIndex += 1
        }
      })
      // 取出选中项放到最上面
      this.widgets.push(this.widgets.splice(this.rightClickIndex, 1)[0]);
      // 重置高亮组件
      for (let i = 0; i < this.widgets.length; i++) {
        this.$refs.widgets[i].$refs.draggable.setActive(false);
      }
      this.$refs.widgets[this.widgets.length -1].$refs.draggable.setActive(true);
    },
    // 上移一层
    moveupLayer() {
      // 最上层不移动
      if (this.rightClickzIndex >= this.widgets.length - 1) return
      // 数组中zindex交换位置
      this.widgets[this.rightClickIndex].value.position.zIndex += 1
      this.widgets[this.rightClickIndex - 1].value.position.zIndex -= 1
      // 数组交换位置
      this.widgets[this.rightClickIndex] = this.widgets.splice(
        this.rightClickIndex - 1,
        1,
        this.widgets[this.rightClickIndex]
      )[0];
      // 重置高亮组件
      for (let i = 0; i < this.widgets.length; i++) {
        if (this.rightClickIndex - 1 === i) {
          this.$refs.widgets[i].$refs.draggable.setActive(true);
        } else {
          this.$refs.widgets[i].$refs.draggable.setActive(false);
        }
      }
    },
    // 下移一层
    movedownLayer() {
      // 最下层不移动
      if (this.rightClickzIndex <= 0) return
      // 数组中zindex交换位置
      this.widgets[this.rightClickIndex].value.position.zIndex -= 1
      this.widgets[this.rightClickIndex + 1].value.position.zIndex += 1
      // 数组交换位置
      this.widgets[this.rightClickIndex] = this.widgets.splice(
        this.rightClickIndex + 1,
        1,
        this.widgets[this.rightClickIndex]
      )[0];
      // 重置高亮组件
      for (let i = 0; i < this.widgets.length; i++) {
        if (this.rightClickIndex + 1 === i) {
          this.$refs.widgets[i].$refs.draggable.setActive(true);
        } else {
          this.$refs.widgets[i].$refs.draggable.setActive(false);
        }
      }
    },
    /***************移动缩放画布，框选组件*****************/
    // 鼠标滚动缩放画布
    rollImg(e) {
      // 按住alt的是时候触发
      if (!this.keys.alt) return;
      // 向上滚动为150，向下滚动为-150
      if (e.wheelDelta > 0) {
        if (this.workbenchScale >= 5) return;
        this.workbenchScale += 0.1
        this.rulerState.scale += 0.1
      } else {
        if (this.workbenchScale <= 0.2) return;
        this.workbenchScale -= 0.1
        this.rulerState.scale -= 0.1
      }
      this.$nextTick(() => {
        this.handleScroll()
      })
      return true;
    },
    // 鼠标移动
    handleMouseMove(e) {
      // 计算鼠标移动偏移量 = 鼠标的移动距离-鼠标按下的初始距离 => 改变滚动条，实现拖动画布，
      let mouseMoveX = e.clientX - this.mouseDownPosition.left;
      let mouseMoveY = e.clientY - this.mouseDownPosition.top;
      // 按下空格拖拽画布
      if(this.keys.space) {
        // 计算鼠标移动偏移量 = 鼠标的移动距离-鼠标按下的初始距离 => 改变滚动条，实现拖动画布，
        document.querySelector('.workbench-container').scrollTo(this.offsetLeft - mouseMoveX, this.offsetTop - mouseMoveY);
      } else {
        // 没有按下空格出现拖选框
        const rectDiv = document.querySelector('.rectDiv');

        rectDiv.style.display = 'block'
        rectDiv.style.width = Math.abs(mouseMoveX) + 'px' ;
        rectDiv.style.height = Math.abs(mouseMoveY) + 'px' ;
        rectDiv.style.left = e.clientX > this.mouseDownPosition.left ? this.mouseDownPosition.left + 'px' : e.clientX + 'px'
        rectDiv.style.top = e.clientY > this.mouseDownPosition.top ? this.mouseDownPosition.top + 'px' : e.clientY + 'px'
      }
    },
    // 鼠标按下画布
    mousedowncont(e) {
      // 显示大屏配置
      this.setOptionsOnClickScreen()

      // 记录鼠标按下时相对窗口的位置，用于画布拖动和拖选框
      this.$nextTick(() => {
        this.mouseDownPosition.left = e.clientX;
        this.mouseDownPosition.top = e.clientY;

        e.preventDefault();  // 阻止默认行为
        e.stopPropagation(); // 阻止事件冒泡

        const container = document.querySelector('.screen-container')
        container.addEventListener('mousemove', this.handleMouseMove, false)
      })
    },
    // 鼠标在组件上抬起的时候隐藏拖选框
    mouseupcontWid() {
      const rectDiv = document.querySelector('.rectDiv');
      rectDiv.style.display = 'none';
      rectDiv.style.width = 0;
      rectDiv.style.height = 0;
    },
    // 鼠标抬起
    mouseupcont(e) {
      this.$nextTick(() => {
        const canvasRect = document.querySelector(".canvash").getBoundingClientRect();
        // 得到选框四个角的定位值
        const x1 = this.getFixed(this.mouseDownPosition.left - canvasRect.left)
        const x2 = this.getFixed(e.clientX - canvasRect.left)
        const y1 = this.getFixed(this.mouseDownPosition.top - canvasRect.top)
        const y2 = this.getFixed(e.clientY - canvasRect.top)

        // 计算在画布中框的位置
        const x11 = this.getFixed((x1 * this.dashboard.width) / canvasRect.width)
        const x22 = this.getFixed((x2 * this.dashboard.width) / canvasRect.width)
        const y11 = this.getFixed((y1 * this.dashboard.height) / canvasRect.height)
        const y22 = this.getFixed((y2 * this.dashboard.height) / canvasRect.height)

        // 框选的组件高亮，其他组件取消高亮
        const draggableArr = this.$refs.widgets;
        for (let i = 0; i < draggableArr.length; i++) {
          this.$refs.widgets[i].$refs.draggable.setActive(false);
        }
        this.widgets.map((item, index) => {
          // 获取每个组件四个角的定位值
          let x111 = item.value.position.left;
          let x222 = this.getFixed(item.value.position.left + item.value.position.width);
          let y111 = item.value.position.top;
          let y222 = this.getFixed(item.value.position.top + item.value.position.height);
          // 计算组件是否包含在内
          let isx1 = x11 < x22 ? x111 >= x11 && x111 <= x22 : x111 <= x11 && x111 >= x22;
          let isx2 = x11 < x22 ? x222 >= x11 && x222 <= x22 : x222 <= x11 && x222 >= x22;
          let isy1 = y11 < y22 ? y111 >= y11 && y111 <= y22 : y111 <= y11 && y111 >= y22;
          let isy2 = y11 < y22 ? y222 >= y11 && y222 <= y22 : y222 <= y11 && y222 >= y22;
          // 包含在内，激活组件
          if(isx1 && isx2 && isy1 && isy2){
            this.widgetIndex.push(item.id);
            this.widgetComponent.push(item);
            this.$refs.widgets[index].$refs.draggable.setActive(true);
          }
          // 显示对齐方式
          if(this.widgetIndex.length > 1) {
            this.activeName = "multiple";
          }
        })

        // 隐藏拖选框
        const rectDiv = document.querySelector('.rectDiv');
        rectDiv.style.display = 'none';
        rectDiv.style.width = 0;
        rectDiv.style.height = 0;

        // 画布移动：按下空格键，卸载移动监听，重置画布位置
        let mouseMoveX = e.clientX - this.mouseDownPosition.left;
        let mouseMoveY = e.clientY - this.mouseDownPosition.top;

        e.preventDefault();  // 阻止默认行为
        e.stopPropagation(); // 阻止事件冒泡


        const container = document.querySelector('.screen-container')
        container.removeEventListener('mousemove', this.handleMouseMove, false)
        if(!this.keys.space) return
        this.offsetLeft = this.offsetLeft - mouseMoveX;
        this.offsetTop = this.offsetTop - mouseMoveY;
      })
    },
    // 组件微调方法
    handleMoveLittle(keyCode, e) {
      let step = 1 * this.stepScale;
      // 获取所有激活项
      this.widgetComponent.map(item => {
        // 监听上下左右
        if (keyCode == 38) {
          //上
          e.preventDefault()
          item.value.position.top = this.getFixed(item.value.position.top - step);
        } else if (keyCode == 37) {
          //左
          e.preventDefault()
          item.value.position.left = this.getFixed(item.value.position.left - step);
        } else if (keyCode == 40) {
          //下
          e.preventDefault()
          item.value.position.top = this.getFixed(item.value.position.top + step);
        } else if (keyCode == 39) {
          //右
          e.preventDefault()
          item.value.position.left = this.getFixed(item.value.position.left + step);
        }
      })
    },
    // 监听滚动条,计算标尺的移动
    handleScroll() {
      const screensRect = document.querySelector(".workbench-container").getBoundingClientRect();
      const canvasRect = document.querySelector(".canvash").getBoundingClientRect();

      // 标尺开始的刻度
      const startX = (screensRect.left - canvasRect.left) / this.rulerState.scale;
      const startY = (screensRect.top - canvasRect.top) / this.rulerState.scale;

      this.rulerState.startX = startX;
      this.rulerState.startY = startY;
    },
    // 标尺辅助线
    handleLine(lines) {
      this.lines = lines;
    },
    handleCornerClick() {
      return;
    },

  },
};
</script>

<style scoped lang="less">
.mr10 {
  margin-right: 10px;
}

.ml20 {
  margin-left: 20px;
}

.border-right {
  border-right: 1px solid #273b4d;
}

.border-left {
  border-left: 1px solid #273b4d;
}

.el-icon-arrow-down {
  font-size: 10px;
}

.is-active {
  // background: #31455d !important;
  background: #409EFF !important;
  color: #373d41 !important;
}

.layout {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  width: 100%;
  height: 100vh;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;

  .layout-left {
    display: inline-block;
    height: 100%;
    box-sizing: border-box;
    -webkit-box-sizing: border-box;
    border: 0px;
    background-color: #263445;

    //工具栏一个元素
    .tools-item {
      display: flex;
      position: relative;
      width: 100%;
      height: 48px;
      align-items: center;
      -webkit-box-align: center;
      padding: 0 6px;
      cursor: pointer;
      font-size: 12px;
      margin-bottom: 1px;

      &:hover {
        background: #31455d;
      }

      .tools-item-icon {
        color: #409eff;
        margin-right: 10px;
        width: 53px;
        height: 30px;
        line-height: 30px;
        text-align: center;
        display: block;
        border: 1px solid #3a4659;
        background: #282a30;
      }

      .tools-item-text {
      }
    }
  }

  .layout-left-fold {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    height: 100vh;

    font-size: 12px;
    overflow: hidden;
    background-color: #242a30;
    cursor: pointer;
    padding-top: 26%;

    i {
      font-size: 18px;
      width: 18px;
      height: 23px;
      margin-left: 0px;
      color: #bfcbd9;
    }
  }

  .layout-middle {
    flex: 1;
    position: relative;
    //width: calc(100% - 445px);
    height: 100%;
    background-color: rgb(36, 42, 48);
    box-sizing: border-box;
    -webkit-box-sizing: border-box;
    border: 1px solid rgb(36, 42, 48);
    align-items: center;
    vertical-align: middle;
    text-align: center;

    .top-button {
      display: flex;
      flex-direction: row;
      height: 40px;
      line-height: 40px;

      .btn {
        margin-right: 8px;
        margin-top: 4px;
        width: 50px;
        height: 32px;
        line-height: 26px;
        font-size: 14px;
        text-align: center;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        background: #303640;
        transition: 0.2s;
        color: #fff;
        border: 1px solid #545454;
        border-radius: 4px;

        .el-icon-arrow-down {
          transform: rotate(0deg);
          -ms-transform: rotate(0deg); /* IE 9 */
          -moz-transform: rotate(0deg); /* Firefox */
          -webkit-transform: rotate(0deg); /* Safari 和 Chrome */
          -o-transform: rotate(0deg); /* Opera */
          transition: all 0.4s ease-in-out;
        }

        &:hover {
          background: rgb(25, 29, 34);

          .el-icon-arrow-down {
            transform: rotate(180deg);
            -ms-transform: rotate(180deg); /* IE 9 */
            -moz-transform: rotate(180deg); /* Firefox */
            -webkit-transform: rotate(180deg); /* Safari 和 Chrome */
            -o-transform: rotate(180deg); /* Opera */
            transition: all 0.4s ease-in-out;
          }
        }
      }
    }

    .workbench-container {
      position: absolute;
      top: 26px;
      left: 20px;
      overflow: scroll;
      -webkit-transform-origin: 0 0;
      background: url("../../../assets/images/bg1.png");
      transform-origin: 0 0;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
      margin: 0;
      padding: 0;
      z-index: 4;
      &::-webkit-scrollbar {
        width: 7px;
        height: 7px;
      }

      &::-webkit-scrollbar-track,
      &::-webkit-scrollbar-thumb {
        border-radius: 1px;
        border: 0 solid transparent;
      }

      &::-webkit-scrollbar-track-piece {
        /*修改滚动条的背景和圆角*/
        background: #191e22;
        -webkit-border-radius: 7px;
      }

      &::-webkit-scrollbar-track {
        box-shadow: 1px 1px 5px rgba(144, 146, 152, 0.3) inset;
      }

      &::-webkit-scrollbar-thumb {
        min-height: 20px;
        background-clip: content-box;
        box-shadow: 0 0 0 5px rgba(144, 146, 152, 0.3) inset;
      }

      &::-webkit-scrollbar-corner {
        background: transparent;
      }

      /*修改垂直滚动条的样式*/
      &::-webkit-scrollbar-thumb:vertical {
        background-color: rgba(144, 146, 152, 0.3);
        -webkit-border-radius: 7px;
      }

      /*修改水平滚动条的样式*/
      &::-webkit-scrollbar-thumb:horizontal {
        background-color: rgba(144, 146, 152, 0.3);
        -webkit-border-radius: 7px;
      }
      .screen-container {
        position: relative;
        width: 5000px;
        height: 3000px;
        display: flex;
        justify-content: center;
        align-items: center;
        .rectDiv {
          position: fixed;
          border: solid 1px #40e3dd;
          background: rgba(0, 255, 255, 0.3);
          z-index: 99999;
          width: 0;
          height: 0;
          display: none;
        }
      }

      .workbench {
        background-color: #1e1e1e;
        position: relative;
        -webkit-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
        -webkit-transform-origin: 0 0;
        transform-origin: 0 0;
        margin: 0;
        padding: 0;
        // position: absolute;
        // left: 50%;
        // top: 50%;
      }

      .bg-grid {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-size: 30px 30px, 30px 30px;
        background-image: linear-gradient(
            hsla(0, 0%, 100%, 0.1) 1px,
            transparent 0
          ),
          linear-gradient(90deg, hsla(0, 0%, 100%, 0.1) 1px, transparent 0);
        z-index: -2;
      }
    }
    .vueRuler {
      width: 100%;
      height: 100%;
      position: absolute;
      z-index: 2;
    }

    .bottom-text {
      width: 100%;
      color: #a0a0a0;
      font-size: 16px;
      position: absolute;
      bottom: 20px;
    }
  }

  .layout-right {
    display: inline-block;
    height: 100%;
  }

  /deep/ .el-tabs--border-card {
    border: 0;

    .el-tabs__header {
      .el-tabs__nav {
        .el-tabs__item {
          background-color: #242f3b;
          border: 0px;
        }

        .el-tabs__item.is-active {
          background-color: #31455d;
        }
      }
    }

    .el-tabs__content {
      background-color: #242a30;
      height: calc(100vh - 39px);
      overflow-x: hidden;
      overflow-y: auto;

      .el-tab-pane {
        color: #bfcbd9;
      }

      &::-webkit-scrollbar {
        width: 5px;
        height: 14px;
      }

      &::-webkit-scrollbar-track,
      &::-webkit-scrollbar-thumb {
        border-radius: 1px;
        border: 0 solid transparent;
      }

      &::-webkit-scrollbar-track-piece {
        /*修改滚动条的背景和圆角*/
        background: #29405c;
        -webkit-border-radius: 7px;
      }

      &::-webkit-scrollbar-track {
        box-shadow: 1px 1px 5px rgba(116, 148, 170, 0.5) inset;
      }

      &::-webkit-scrollbar-thumb {
        min-height: 20px;
        background-clip: content-box;
        box-shadow: 0 0 0 5px rgba(116, 148, 170, 0.5) inset;
      }

      &::-webkit-scrollbar-corner {
        background: transparent;
      }

      /*修改垂直滚动条的样式*/
      &::-webkit-scrollbar-thumb:vertical {
        background-color: #00113a;
        -webkit-border-radius: 7px;
      }

      /*修改水平滚动条的样式*/
      &::-webkit-scrollbar-thumb:horizontal {
        background-color: #00113a;
        -webkit-border-radius: 7px;
      }
    }
  }
}

ul,
li {
  list-style: none;
  margin: 0;
  padding: 0;
}

.nav {
  width: 40px;
  padding: 0;
  list-style: none;
  /* overflow: hidden; */
}

.nav {
  zoom: 1;
}

.nav:before,
.nav:after {
  content: "";
  display: table;
}

.nav:after {
  clear: both;
}

.nav > li {
  width: 55px;
  text-align: left;
  position: relative;
}

.nav > li a {
  float: left;
  padding: 12px 30px;
  color: #999;
  font: bold 12px;
  text-decoration: none;
}

.nav > li:hover {
  color: #788994;
}

.nav > li ul {
  visibility: hidden;
  position: absolute;
  z-index: 1000;
  list-style: none;
  left: 0;
  padding: 0;
  background-color: rgb(36, 42, 48);
  opacity: 0;
  _margin: 0;
  width: 120px;
  transition: all 0.2s ease-in-out;
}

.nav > li:hover > ul {
  opacity: 1;
  visibility: visible;
  margin: 0;

  li:hover {
    background-color: rgb(25, 29, 34);
  }
}

.nav ul li {
  float: left;
  display: block;
  border: 0;
  width: 100%;
  font-size: 12px;
}

.nav ul a {
  padding: 10px;
  width: 100%;
  display: block;
  float: none;
  height: 120px;
  border: 1px solid #30445c;
  background-color: rgb(25, 29, 34);
  transition: all 0.2s ease-in-out;
}

.nav ul a:hover {
  border: 1px solid #3c5e88;
}

.nav ul li:first-child > a:hover:before {
  border-bottom-color: #04acec;
}

.nav ul ul {
  top: 0;
  left: 120px;
  width: 400px;
  height: 300px;
  overflow: auto;
  padding: 10px;
  _margin: 0;
}

.nav ul ul li {
  width: 120px;
  height: 120px;
  margin-right: 3px;
  display: block;
  float: left;
}

.nav .item {
  padding: 5px;
}

/deep/ .vue-ruler-h {
  width: 98%;
  opacity: 0.7;
}

/deep/ .vue-ruler-v {
  opacity: 0.7;
}
// 标尺
.sketchRule {
  z-index: 999;
  // height: calc(100vh - 52px);
}
.bigscreenWorkbench {
  position: relative;
  .refer-line-img {
    position: absolute;
    left: 0;
    top: 0;
    z-index: 9999999999;
    .img1 {
      width: 30px;
      margin: -2px 0 0 -8px;
    }
    .img2 {
      margin: -4px 0 0 -5px
    }
  }
}
.footer {
  position: absolute;
  bottom: 8px;
  text-align: center;
  width: 100%;
  color: #9f9f9f;
  font-size: 13px;
}
</style>
